package com.coreform;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import android.content.Context;

import com.gdth.model.Item;
import com.gdth.utils.FileUtil;

public class XmlUtil {	
	/**
     * 遍历数据源，为DrawDownList获取数据
     * @param context
     * @param name
     * @return
     */
	public static List<Item> GetDataSourceByItem(Context context, String name){
		List<Item> itemList = null;
		
		InputStream is = FileUtil.readFileByAssets(context, "datasource.xml");
    	
		DocumentBuilderFactory factory = null;
        DocumentBuilder builder=null;
        Document document=null;
         
        try {
            factory = DocumentBuilderFactory.newInstance();;
            builder=factory.newDocumentBuilder();
            
            document=builder.parse(is);
            
            //获取element元素节点
            NodeList nodeAttributes = (NodeList) document.getElementsByTagName("datasource");
       
            int nodeLength = nodeAttributes.getLength();
            
            for(int i=0 ; i < nodeLength; i++){
                //获取river元素节点
                Element datasource=(Element)(nodeAttributes.item(i));
                
                String names = datasource.getAttribute("name");
                
                if (names.equals(name)){
                	itemList = new ArrayList<Item>();
                	
//	                String type = datasource.getAttribute("type");
	                
	                NodeList items = (NodeList) datasource.getElementsByTagName("item");
	                
	                int itemLength = items.getLength();
	                
	                for (int j = 0; j < itemLength; j++){
	                	Element item =(Element) (items.item(j));
	                	String key = item.getAttribute("key");
	                	String val = item.getFirstChild().getNodeValue();
	                	
	                	Item mItem = new Item();
	                	mItem.setKey(key);
	                	mItem.setValue(val);
	                	itemList.add(mItem);
	                }
	                
	                break;
                }
            }
            
        }catch (IOException e) {
            e.printStackTrace();
        } catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} 
        
        return itemList; 
	}
}
